package com.ideafactory.client.print.icod;

import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.ideafactory.client.beans.OrderGoodsBean;
import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.APP;
import com.szsicod.print.escpos.PrinterAPI;
import com.szsicod.print.io.InterfaceAPI;
import com.szsicod.print.io.UsbNativeAPI;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class IcodPrinterManager {

    private final String TAG = "IcodPrinter";

    private final int PRINT_RESULT = 10001;

    static {
        //如果使用UsbNativeAPI 必须加载 适用root板 这个不需要权限窗口和申请权限
        System.loadLibrary("usb1.0");
    }

    private volatile static IcodPrinterManager instance;

    private PrinterAPI mPrinter;
    private DataUtils dataUtils;

    private Runnable runnable;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static IcodPrinterManager getIns() {
        if (instance == null) {
            synchronized (IcodPrinterManager.class) {
                if (instance == null) {
                    instance = new IcodPrinterManager();
                }
            }
        }
        return instance;
    }

    private IcodPrinterManager() {
        mPrinter = PrinterAPI.getInstance();
        dataUtils = DataUtils.getInstance(APP.getAPP());
    }

    public void connect() {
        runnable = new Runnable() {
            @Override
            public void run() {
                if (mPrinter.isConnect()) {
                    mPrinter.disconnect();
                }
                InterfaceAPI io = new UsbNativeAPI();
                handler.obtainMessage(mPrinter.connect(io)).sendToTarget();
            }
        };
        new Thread(runnable).start();
    }

    public void disConnect() {
        if (mPrinter.isConnect()) {
            mPrinter.disconnect();
        }
    }

    public int checkState() {
        if (mPrinter.isConnect()) {
            byte[] bytes = new byte[]{0x10, 0x04, 0x01, 0x10, 0x04, 0x02, 0x10, 0x04, 0x03, 0x10, 0x04, 0x04};
            mPrinter.sendOrder(bytes);
            byte[] ret = new byte[4];
            mPrinter.readIO(ret, 0, ret.length, 2 * 1000);
            d("状态：" + StatusDescribe.getStatusDescribe(mPrinter.getStatus()) + "   " + dataUtils.bytesToHexString(ret));
            return 1;
        } else {
            d("状态：未连接");
            return -1;
        }
    }

    public void printText(final List<OrderGoodsBean> list, UsbDevice mUsbDev1, final String shopName, final String shopAddress, final String AllMoney, final String CallNum, final String PackMoney, final int  isPack, final String preMoney, final String realMoney) {
        runnable = new Runnable() {
            @Override
            public void run() {
                if (mPrinter.isConnect()) {

                    mPrinter.setAlignMode(1);
                    mPrinter.setLineSpace(36);
                    //进纸
                    mPrinter.printAndFeedLine(1);

                    printText(shopName);
                    printText(shopAddress);
                    mPrinter.setAlignMode(0);
                    printText("------------------------------------------------");
                    printText(APP.getAPP().getResources().getString(R.string.print_OrderNumber) + CallNum);
                    printText("------------------------------------------------");

                    List<String> mListTab1 = new ArrayList<>();
                    List<String> mListTab2 = new ArrayList<>();
                    mListTab1.add(APP.getAPP().getResources().getString(R.string.print_Goods) + "                        ");
                    mListTab2.add(APP.getAPP().getResources().getString(R.string.print_UnitPriceQquantity) + "");
                    for (int i = 0; i < list.size(); i++) {
                        int lenth = list.get(i).getName().length();
                        if (lenth > 7){
                            mListTab1.add(list.get(i).getName().substring(0,7) + "              ");
                        }else if (lenth == 7){
                            mListTab1.add(list.get(i).getName()+"              ");
                        }else if (lenth == 6){
                            mListTab1.add(list.get(i).getName()+"                ");
                        }else if (lenth == 5){
                            mListTab1.add(list.get(i).getName()+"                  ");
                        }else if (lenth == 4){
                            mListTab1.add(list.get(i).getName()+"                    ");
                        }else if (lenth == 3){
                            mListTab1.add(list.get(i).getName()+"                      ");
                        }else if (lenth == 2){
                            mListTab1.add(list.get(i).getName()+"                        ");
                        }else if (lenth == 1){
                            mListTab1.add(list.get(i).getName()+"                          ");
                        }
                        mListTab2.add(list.get(i).getPrice() + "*" + list.get(i).getCount());
                    }
                    for(int i = 0; i < list.size() + 1; i++){
                        printText(mListTab1.get(i) + mListTab2.get(i));
                    }

                    if (isPack==1){
                        printText(APP.getAPP().getResources().getString(R.string.print_packingFee) + PackMoney + APP.getAPP().getResources().getString(R.string.print_yuan));
                    }
                    printText("------------------------------------------------");
                    BigDecimal packBigDecimal = new BigDecimal(PackMoney);
                    printText(APP.getAPP().getResources().getString(R.string.print_OrderAmount) + "                    " + packBigDecimal.add(new BigDecimal(realMoney)).setScale(2).toString() + APP.getAPP().getResources().getString(R.string.print_yuan));
                    printText(APP.getAPP().getResources().getString(R.string.print_DiscountedPrice)+"                    " + packBigDecimal.add(new BigDecimal(preMoney)).setScale(2).toString() + APP.getAPP().getResources().getString(R.string.print_yuan));

                    if (AllMoney.equals("0.0") && preMoney.length() > 3){
                        printText(APP.getAPP().getResources().getString(R.string.print_actuallyPaid) + "                    " + packBigDecimal.add(new BigDecimal("0.0")).setScale(2).toString() + APP.getAPP().getResources().getString(R.string.print_yuan));
                    } else {
                        printText(APP.getAPP().getResources().getString(R.string.print_actuallyPaid) + "                    " + packBigDecimal.add(new BigDecimal(AllMoney)).setScale(2).toString() + APP.getAPP().getResources().getString(R.string.print_yuan));
                    }
                    printText("------------------------------------------------");
                    printText(APP.getAPP().getResources().getString(R.string.print_PaymentTime) + sdf.format(new Date()));

                    //进纸
                    mPrinter.printAndFeedLine(1);
                    //切纸
                    mPrinter.cutPaper(66, 0);
                } else {
                    d("打印：未连接");
                }
            }
        };
        new Thread(runnable).start();
    }

    public void printText(String content) {
        try {
            int ret = mPrinter.printString(content, "gbk", true);
            handler.obtainMessage(PRINT_RESULT, ret == PrinterAPI.SUCCESS ? "打印成功" : "打印失败").sendToTarget();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public void printTest() {
        printText("测试测试测试测试测试\n\n\n\n测试测试测试测试\n\n\n");
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PrinterAPI.SUCCESS:
                    d("连接成功");
                    break;
                case PrinterAPI.FAIL:
                case PrinterAPI.ERR_PARAM:
                    d("连接失败");
                    break;
                case PRINT_RESULT:
                    d(msg.obj + "");
                    break;
            }
        }
    };

    private void d(String logStr) {
        Log.d(TAG, logStr);
    }

}
